package com.pin.si.www.example.controller;

import com.pin.si.www.common.pojo.result.CommonResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

@Tag(name = "测试虚拟线程")
@RestController
@RequestMapping("/test")
public class TestVirtualController {

    @Resource
    private ApplicationContext applicationContext;

    @Operation(summary = "虚拟线程信息")
    @GetMapping("/virtual-thread-info")
    public CommonResult<String> testThread() {
        Thread currentThread = Thread.currentThread();

        // 获取 TestController bean 实例
        TestVirtualController testVirtualController = applicationContext.getBean(TestVirtualController.class);
        testVirtualController.testAsync();

        return CommonResult.success(String.format("""
                线程信息:
                - 线程名称: %s
                - 是否为虚拟线程: %b
                - 线程组名称: %s
                """,
                currentThread.getName(),
                currentThread.isVirtual(),
                currentThread.getThreadGroup().getName()
        ));
    }

    @Async
    protected void testAsync() {
        Thread currentThread = Thread.currentThread();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.printf("""
                        线程信息:
                        - 线程名称: %s
                        - 是否为虚拟线程: %b
                        - 线程组名称: %s
                        %n""",
                currentThread.getName(),
                currentThread.isVirtual(),
                currentThread.getThreadGroup().getName()
        );
    }

    @Scheduled(fixedRate = 600000)
    public void scheduledTask() {
        System.out.printf("""
                定时任务执行时间: %s
                线程信息:
                - 线程名称: %s
                - 是否为虚拟线程: %b
                - 线程组名称: %s
                %n""",
                LocalDateTime.now(),
                Thread.currentThread().getName(),
                Thread.currentThread().isVirtual(),
                Thread.currentThread().getThreadGroup().getName()
        );
    }

}
